using CQIE.LabAssist.DataAccesss;
using CQIE.LabAssist.Models;
using CQIE.LabAssist.PublicHelp;
using FreeRedis;
using LAB.MANAGE;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
var configuration = builder.Configuration;

//Consul
builder.Services.RegisterConsul(builder.Configuration);


// 添加服务到容器
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddControllers();
builder.Services.AddScoped<_DbContext>();
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<IFloorService, FloorService>();
builder.Services.AddScoped<ILaboratoryService, LaboratoryService>();
builder.Services.AddScoped<IMangmentService, MangmentService>();
builder.Services.AddScoped<IBuildingService, BuildingService>();
//builder.Services.AddScoped<ICheckService, CheckService>();
builder.Services.AddScoped<IFirstService, FirstService>();




//builder.Services.AddScoped<CQIE.Books.DataAccesss.Imps.IInventoryService, CQIE.Books.DataAccesss.Imps.IInventoryService>();

// Jwt注册
builder.Services.AddSingleton(new JwtHelp(configuration));

// 跨域配置
var corsname = "any";
builder.Services.AddCors(options =>
{
    options.AddPolicy(corsname, builder =>
    {
        builder.SetIsOriginAllowed(_ => true).AllowAnyMethod().AllowAnyHeader().AllowCredentials();
    });
});


#region Redis服务
//注册缓存服务
builder.Services.AddResponseCaching();
builder.Services.AddDistributedMemoryCache(); // 注册 IDistributedCache 服务
                                              //记得添加app.UseSession();在后面！！！
                                              //注册Session服务
builder.Services.Configure<CookiePolicyOptions>(options =>
{
    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
    options.CheckConsentNeeded = context => false; //这里要改为false，默认是true，true的时候session无效
    options.MinimumSameSitePolicy = SameSiteMode.None;
});
builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromMinutes(30);//30分钟session失效
    options.Cookie.HttpOnly = false;
}
);

builder.Services.AddHttpContextAccessor();
string _connectionString = builder.Configuration.GetConnectionString("Redis")!;
builder.Services.AddDistributedRedisCache(options =>
{
    options.Configuration = _connectionString;
    options.InstanceName = "LabManage";
});
#endregion


// 配置JWT认证
builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidIssuer = configuration["Jwt:Issuer"],
        ValidateAudience = true,
        ValidAudience = configuration["Jwt:Audience"],
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:SecretKey"])),
        ValidateLifetime = true,
        ClockSkew = TimeSpan.FromSeconds(30),
        RequireExpirationTime = true,
    };
});

//注册api文档说明
builder.Services.AddSwaggerGen(config =>
{
    #region 配置API文档说明
    config.SwaggerDoc("v1", new OpenApiInfo
    {
        Version = "v1",
        Title = "宇宙无敌霹雳webapi",
        Description = "文档说明",
        Contact = new OpenApiContact
        {
            Name = "Name",
            Email = "test"
        }
    });

    var basePath = AppContext.BaseDirectory;
    var xmlPath = Path.Combine(basePath, "CQIE.LabAssist.xml");
    config.IncludeXmlComments(xmlPath, true);
    #endregion
});
 
var app = builder.Build();

// 配置HTTP请求管道
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();

    app.UseSwaggerUI(options =>
    {
        options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
    });
   
}

    app.UseHttpsRedirection();

app.UseStaticFiles();

// 调用中间件：UseAuthentication（认证），必须在所有需要身份认证的中间件前调用
app.UseAuthentication();
app.UseAuthorization();
app.UseCors(builder => builder
    .AllowAnyOrigin()
    .AllowAnyMethod()
    .AllowAnyHeader());

app.MapControllers();



app.Run();
